package com.cloud.wms.ui.main.activity;

import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Environment;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageView;

import androidx.appcompat.widget.ListPopupWindow;

import com.cloud.core.eventBus.Event;
import com.cloud.core.tools.ActivityManager;
import com.cloud.core.utils.FileUtil;
import com.cloud.core.utils.IntentUtil;
import com.cloud.core.utils.NumberUtils;
import com.cloud.wms.BuildConfig;
import com.cloud.wms.R;
import com.cloud.wms.app.FineExApplication;
import com.cloud.wms.base.BaseActivity;
import com.cloud.wms.config.CacheConfig;
import com.cloud.wms.config.EventConfig;
import com.cloud.wms.entity.UpdateInfoBean;
import com.cloud.wms.http.download.DownloadProgressBean;
import com.cloud.wms.http.url.SiteManager;
import com.cloud.wms.ui.main.contract.LoginContract;
import com.cloud.wms.ui.main.entity.RemoteLoginEntity;
import com.cloud.wms.ui.main.presnter.LoginPresenter;
import com.cloud.wms.ui.returned.inquire.FaceSheetStartActivity;
import com.cloud.wms.widget.dialog.AlertDialogBuilder;
import com.cloud.wms.widget.dialog.UpdateDialog;
import com.tbruyelle.rxpermissions2.RxPermissions;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.util.ArrayList;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * @Author:Chen
 * @Date: 2021-01-14 15:48
 * @Description:
 */
public class LoginActivity extends BaseActivity<LoginPresenter> implements LoginContract.View, UpdateDialog.DownloadListener {
    @BindView(R.id.et_account)
    EditText etAccount;
    @BindView(R.id.et_pwd)
    EditText etPwd;
    @BindView(R.id.iv_login_title)
    ImageView ivLoginTitle;
    @BindView(R.id.iv_history_account)
    ImageView ivHistoryAccount;
    private RxPermissions rxPermissions;
    private boolean permissionState;
    private ArrayList<String> accountRecord;
    private ArrayAdapter<String> adapter;
    private ListPopupWindow popupMenu;
    private UpdateDialog mDialog;
    private UpdateInfoBean.VerBean mData;

    @Override
    protected int getResId() {
        return R.layout.activity_main_login;
    }

    @Override
    protected void setupComponent() {
        getActivityComponent().inject(this);
    }

    @Override
    protected void initBar() {
    }

    @Override
    protected void initEvent() {
        rxPermissions = new RxPermissions(this);
        mPresenter.checkPermission(rxPermissions);

        accountRecord = mPresenter.loadAccountRecord();

        if (!accountRecord.isEmpty()) {
            etAccount.setText(accountRecord.get(0));
        }
        etAccount.setSelection(etAccount.getText().length());
        popupMenu = initPopupMenu(etAccount);
//        ivLoginTitle.setOnClickListener(v -> {
//            startActivity(new Intent(this, FaceSheetStartActivity.class));
//        });
    }

    private ListPopupWindow initPopupMenu(View v) {
        ListPopupWindow listPopupWindow =
                new ListPopupWindow(this, null, R.attr.listPopupWindowStyle);
        adapter = new ArrayAdapter<String>(
                this,
                R.layout.item_dropdown_popup_login,
                accountRecord);
        listPopupWindow.setAdapter(adapter);
        listPopupWindow.setAnchorView(v);
        listPopupWindow.setOnItemClickListener(
                (parent, view, position, id) -> {
                    etAccount.setText(accountRecord.get(position));
                    etAccount.setSelection(accountRecord.get(position).length());
                    listPopupWindow.dismiss();
                });
        listPopupWindow.setOnDismissListener(() -> ivHistoryAccount.setRotation(0));
        listPopupWindow.setModal(true);
        return listPopupWindow;
    }

    @Override
    public void showPermissionDialog() {
        new AlertDialogBuilder(this)
                .setTitle("权限申请")
                .setMessage("使用本应用需要开启相应手机权限，请确认开启")
                .setPositiveButton("去开启", (dialog, which) -> mPresenter.getPermission(rxPermissions))
                .setNegativeButton("取消", null)
                .show();
    }

    /**
     * 显示更新对话框
     */
    @Override
    public void showUpdateDialog(UpdateInfoBean.VerBean verBean) {
        mData = verBean;
        if (!TextUtils.isEmpty(verBean.getCode()) && getLocalVersion() < NumberUtils.getIntegerValue(verBean.getCode())) {
            mDialog = new UpdateDialog(mContext, verBean.getContent(), this);
            if (!mDialog.isShowing()) {
                mDialog.show();
            }
        }
    }

    /**
     * 获取本地软件版本号
     */
    public static int getLocalVersion() {
        int localVersion = 0;
        try {
            PackageInfo packageInfo = FineExApplication.component().appContext().getApplicationContext()
                    .getPackageManager()
                    .getPackageInfo(FineExApplication.component().appContext().getPackageName(), 0);
            localVersion = packageInfo.versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return localVersion;
    }

    @Override
    public void setPermissionState(boolean permissionState) {
        this.permissionState = permissionState;
        if (permissionState) {
            if (!BuildConfig.DEBUG) {
                mPresenter.getVersion();
            }
        }
    }

    @Override
    public void jumpToBase(RemoteLoginEntity info) {
        adapter.notifyDataSetChanged();
        BaseWarehouseActivity.start(this);
        finish();
    }

    @Override
    public void onSuccess(Message message) {
    }

    @OnClick({R.id.btn_login, R.id.iv_history_account})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_login:
                if (TextUtils.isEmpty(etAccount.getText().toString().trim())) {
                    info("请输入工号");
                    return;
                }
                if (TextUtils.isEmpty(etPwd.getText().toString().trim())) {
                    info("请输入密码");
                    return;
                }
                if (permissionState)
                    mPresenter.loginServer(etAccount.getText().toString().trim(), etPwd.getText().toString().trim());
                else
                    showPermissionDialog();
                break;
            case R.id.iv_history_account:
                if (popupMenu != null) {
                    if (popupMenu.isShowing()) {
                        popupMenu.dismiss();
                    } else {
                        popupMenu.show();
                        ivHistoryAccount.setRotation(180);
                    }
                }
                break;
        }
    }

    @Override
    public void downLoadSuccess(String realPath) {
        FineExApplication.component().toast().shortToast(getString(R.string.download_success));
        File apkFile = new File(realPath);
        if (apkFile.length() == mData.getFileLength()) {
            IntentUtil.installApk(this, apkFile, getPackageName() + ".fileprovider");
            if (mDialog != null && mDialog.isShowing()) {
                mDialog.switchViewState(false);
                mDialog.setProgress(0);
            }
        } else {
            if (mDialog != null && mDialog.isShowing()) {
                mDialog.switchViewState(false);
                mDialog.setProgress(0);
            }
        }
    }

    @Override
    public void downLoadFailure(Throwable throwable) {
        FineExApplication.component().toast().shortToast(getString(R.string.download_fail));
        if (mDialog != null && mDialog.isShowing()) {
            mDialog.setUpdateText("点击重试");
            mDialog.switchViewState(false);
            mDialog.setProgress(0);
        }
    }

    @Override
    public void beginDownload() {
        File apkDir = new File(CacheConfig.APK_APK_FILE);
        if (!apkDir.exists()) {
            apkDir.mkdirs();
        }

        File apkFile = new File(apkDir, mData.getFile());
        if (apkFile.exists()) {
            if (apkFile.length() == mData.getFileLength()) {
                //如果文件存在且文件大小一致 说明最新版本文件已存在 直接安装
                IntentUtil.installApk(this, apkFile, getPackageName() + ".fileprovider");
            } else {
                FileUtil.clearAllFile(CacheConfig.APK_APK_FILE);//删除下载目录下所有apk文件
                mPresenter.downloadApk(SiteManager.DOWNLOAD_BASE_URL + "/" + mData.getCode() + "/" + mData.getFile()
                        , apkFile.getAbsolutePath());
            }
        } else {
            FileUtil.clearAllFile(CacheConfig.APK_APK_FILE);//删除下载目录下所有apk文件
            mPresenter.downloadApk(SiteManager.DOWNLOAD_BASE_URL + "/" + mData.getCode() + "/" + mData.getFile()
                    , apkFile.getAbsolutePath());
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void downloadApkEvent(Event<DownloadProgressBean> downloadApkEvent) {
        if (downloadApkEvent.getCode() == EventConfig.REFRESH_DOWNLOAD_PROGRESS) {
            if (mDialog != null && mDialog.isShowing() && downloadApkEvent.getData().contentLength == mData.getFileLength()) {
                mDialog.switchViewState(true);
                double doubleProgress = ((double) downloadApkEvent.getData().bytesRead) / ((double) downloadApkEvent.getData().contentLength);
                mDialog.setProgress((int) (doubleProgress * 10000));
            }
        }
    }

    @Override
    protected boolean isUseEventBus() {
        return true;
    }

    /**
     * 两次点击退出程序 间隔时间2秒
     */
    private long firstTime = 0;

    @Override
    public void cancelClicked() {
        long secondTime = System.currentTimeMillis();
        if (secondTime - firstTime < 2000) {
            ActivityManager.getInstance().finishAllActivity();
        } else {
            info(getString(R.string.update_force_hint));
            firstTime = System.currentTimeMillis();
        }
    }
}
